package com.xbkj.pgrp.server.dataproxy;

import com.xbkj.pgrp.server.model.app.MileStone;
import com.xbkj.pgrp.server.model.app.Project;
import com.xbkj.pgrp.server.model.app.ProjectResource;
import org.springframework.stereotype.Service;
import xyz.erupt.annotation.fun.DataProxy;
import xyz.erupt.jpa.dao.EruptDao;
import xyz.erupt.upms.model.EruptUserVo;
import xyz.erupt.upms.service.EruptUserService;

import javax.annotation.Resource;
import java.util.Date;


@Service
public class ProjectDataProxy implements DataProxy<Project> {

    @Resource
    private EruptDao eruptDao;


    @Resource
    private EruptUserService eruptUserService;




    public void beforeAdd(Project project) {
        project.setCreateTime(new Date());
        project.setCreateUser(new EruptUserVo(this.eruptUserService.getCurrentUid()));
        project.setUpdateTime(new Date());
        project.setUpdateUser(new EruptUserVo(this.eruptUserService.getCurrentUid()));
    }

    public void beforeUpdate(Project project) {
        project.setUpdateTime(new Date());
        project.setUpdateUser(new EruptUserVo(this.eruptUserService.getCurrentUid()));
        saveMileStones(project);
    }

    @Override
    public void afterAdd(Project project) {
        saveMileStones(project);
    }

    private void saveMileStones(Project project) {
        if (project.getMileStones() != null && project.getMileStones().size() > 0) {
            for (MileStone ms : project.getMileStones()) {
                ms.setProject(project);
                ms.setId(null);
                eruptDao.persist(ms);
            }
            eruptDao.flush();
        }

        if (project.getProjectResources() != null && project.getProjectResources().size() > 0) {
            for (ProjectResource pr : project.getProjectResources()) {
                pr.setProject(project);
                pr.setId(null);
                eruptDao.persist(pr);
            }
            eruptDao.flush();
        }
    }
}
